#pragma once

#include "modules/video_capture/video_capture_factory.h"
//#include "media/engine/webrtcvideocapturerfactory.h"
#include "api/peer_connection_interface.h"
#include "QtWebrtcStream.h"
#include "modules/desktop_capture/desktop_geometry.h"
#include "./Video/test_video_capturer.h"
#include "pc/video_track_source.h"
#include "./Video/vcm_capturer.h"


class CapturerTrackSource : public webrtc::VideoTrackSource 
{
public:
    static rtc::scoped_refptr<CapturerTrackSource> Create() 
    {
        const size_t kWidth = 640;
        const size_t kHeight = 480;
        const size_t kFps = 30;
        std::unique_ptr<webrtc::test::VcmCapturer> capturer;
        std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> info(
            webrtc::VideoCaptureFactory::CreateDeviceInfo());
        if (!info) 
        {
            return nullptr;
        }
        int num_devices = info->NumberOfDevices();
        for (int i = 0; i < num_devices; ++i) 
        {
            capturer = absl::WrapUnique(
                webrtc::test::VcmCapturer::Create(kWidth, kHeight, kFps, i));
            if (capturer) 
            {
                return new rtc::RefCountedObject<CapturerTrackSource>(
                    std::move(capturer));
            }
        }

        return nullptr;
    }

protected:
    explicit CapturerTrackSource(
        std::unique_ptr<webrtc::test::VcmCapturer> capturer)
        : VideoTrackSource(/*remote=*/false), capturer_(std::move(capturer)) {}

private:
    rtc::VideoSourceInterface<webrtc::VideoFrame>* source() override {
        return capturer_.get();
    }
    std::unique_ptr<webrtc::test::VcmCapturer> capturer_;
};

class QtWebrtcLocalStream : public QObject, public QtWebrtcStream
{
	Q_OBJECT

public:
	QtWebrtcLocalStream();
	virtual ~QtWebrtcLocalStream();
	static QtWebrtcLocalStream *GetInstance()
	{
		static QtWebrtcLocalStream *instance = new QtWebrtcLocalStream();
		instance->Init();
		return instance;
	};

	bool Init();

	bool CloseVideo();
	bool OpenCamrea(QString &name);
	bool OpenScreen(int id);
	bool OpenScreen(int id, webrtc::DesktopRect rect);
	bool OpenWindow(int id);

	static webrtc::DesktopRect GetScreenRect(int id);
	static bool GetDeviceById(int id, std::string *device_name, std::wstring *device_key);

Q_SIGNALS:
	void VideoTrackChanged();

private:
	 bool SetCapture(std::unique_ptr<webrtc::VideoTrackSource> video_device); 


private:
	std::once_flag			of;
};

#define _WebrtcLocalStream QtWebrtcLocalStream::GetInstance()
